package main

import (
	"database/sql"
	_ "github.com/glebarez/go-sqlite"
	"github.com/mix-go/xcli"
	"hy_808/command"
	"hy_808/di"
	"hy_808/global"
)

func main() {
	xcli.SetName("808平台对接").
		SetVersion("1.0.2")
	xcli.AddCommand(command.Commands...).Run()
}

func InitDB() {
	db := di.Sqlite()
	logger := di.Logdot()
	var tableName string
	err := db.QueryRow("SELECT name FROM sqlite_master WHERE name='hy_device'").Scan(&tableName)
	if err != nil {
		if err == sql.ErrNoRows {
			logger.Debug("新建表hy_device")
			_, err = db.Exec(`CREATE TABLE "main"."hy_device" (
			  "phone" text NOT NULL ,
			  "device_no" INTEGER NOT NULL DEFAULT 0,
			  "color" INTEGER NOT NULL DEFAULT 0,
			  "token_code" TEXT NOT NULL
			);`)
			if err != nil {
				logger.Error("新建表hy_device失败", err)
				panic(err)
			}
		} else {
			logger.Error("查询表sqlite_master异常", err)
		}
		return
	}
	query, err := db.Query("SELECT phone,device_no,token_code FROM hy_device")
	if err != nil {
		logger.Error("查询表hy_device失败", err)
	}
	for query.Next() {
		var phone, tokenCode string
		var deviceNo int
		query.Scan(&phone, &deviceNo, &tokenCode)
		global.DeviceDBDataMap.Store(phone, global.DeviceDBData{
			DeviceNo:  deviceNo,
			Phone:     phone,
			TokenCode: tokenCode,
		})
	}

}
